package cn.lunkr.sdkdemo.ui.phone;


import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;

import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.navigation.NavigationBarView;

import java.util.Date;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.NavGraph;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import cn.lunkr.base.CApp;
import cn.lunkr.base.entity.mail.MailCalendar;
import cn.lunkr.base.entity.mail.SimpleMail;
import cn.lunkr.base.newnet.result.CalListAccessedCalFolderResult;
import cn.lunkr.base.service.InitService;
import cn.lunkr.base.ui.BasicActivity;
import cn.lunkr.base.util.SystemUtil;
import cn.lunkr.mailui.ui.Contact1sBarFragment;
import cn.lunkr.mailui.ui.CustomPopWindow;
import cn.lunkr.mailui.ui.MailsBarFragment;
import cn.lunkr.mailui.ui.OabActivity;
import cn.lunkr.mailui.ui.PabActivity;
import cn.lunkr.mailui.ui.calendar.ui.CalendarDetailActivity;
import cn.lunkr.mailui.ui.calendar.ui.ScheduleBarFragment;
import cn.lunkr.mailui.ui.calendar.ui.ScheduleFragment;
import cn.lunkr.mailui.ui.listener.MailBarFragmentListener;
import cn.lunkr.sdkdemo.R;
import cn.lunkr.sdkdemo.databinding.ActivityCmMainPhoneBinding;
import cn.lunkr.sdkdemo.util.FixFragmentNavigator;

public class CMMainPhoneActivity extends BasicActivity
        implements FragmentResultListener, MailBarFragmentListener, Contact1sBarFragment.Contact1BarFragmentListener,
        ScheduleBarFragment.ScheduleBarFragmentListener {

    private static final String TAG = "MainActivity";

    public ActivityCmMainPhoneBinding activityMainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityCmMainPhoneBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        Fragment fragmentById = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);

        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.tab_mails, R.id.tab_contacts, R.id.tab_calendar, R.id.tab_me) // , R.id.tab_test
                .build();
//        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavController navController = NavHostFragment.findNavController(fragmentById);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(activityMainBinding.navView, navController);
        setFixNavigator(navController, fragmentById);
//        navController.setGraph(R.navigation.mobile_navigation);
        navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                Log.d(TAG, "onDestinationChanged:" + destination.getId());
                Display dp = getWindowManager().getDefaultDisplay();
                int x = dp.getWidth();
                int y = dp.getHeight();
                Log.d(TAG, "width:" + x + " height:" + y);
                switch (destination.getId()) {
                    case R.id.tab_mails:
                        Log.d(TAG, "邮件 TAB");
                        getToolbar().setVisibility(View.GONE);
                        break;
                    case R.id.tab_contacts:
                        Log.d(TAG, "联系人 TAB");
                        setTitle(R.string.contacts);
                        getToolbar().setVisibility(View.GONE);
                        break;
                    case R.id.tab_calendar:
                        Log.d(TAG, "我 TAB");
                        setTitle(R.string.calendar);
                        getToolbar().setVisibility(View.GONE);
                        removeUnread(R.id.tab_mails);
                        break;
                    case R.id.tab_me:
                        Log.d(TAG, "测试");
//                        setTabUnread(R.id.tab_mails, 0);
//                        setTabUnread(R.id.tab_calendar, 22);
//                        setTabUnread(R.id.tab_me, 800);
//                        MailManager.getInstance().onRestart();
                        getToolbar().setVisibility(View.VISIBLE);
                        setTitle(R.string.me);
                        break;
                }
            }
        });
        //activityMainBinding.navView.setItemIconTintList(null);
        initFragAction();
        startInitServie(InitService.OAB_CALLBACK);
    }

    private boolean isTabletDevice(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
                Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    private void setFixNavigator(NavController navController, Fragment fragmentById) {
        NavigatorProvider navigatorProvider = navController.getNavigatorProvider();
        FixFragmentNavigator fixFragmentNavigator = new FixFragmentNavigator(this, fragmentById.getChildFragmentManager(), fragmentById.getId());
        navigatorProvider.addNavigator(fixFragmentNavigator);
        NavGraph navDestinations = new InitPhoneNavGraph().init(CMMainPhoneActivity.this, navigatorProvider, fixFragmentNavigator);
        navController.setGraph(navDestinations);
        activityMainBinding.navView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                navController.navigate(item.getItemId());
                return true;
            }
        });
    }

    /**
     * @param tabId R.id.tab_mails, R.id.tab_contacts, R.id.tab_me, R.id.tab_test
     */
    public void setCuIndex(int tabId) {
        activityMainBinding.navView.postDelayed(new Runnable() {
            @Override
            public void run() {
                //  activityMainBinding.navView.setSelectedItemId(activityMainBinding.navView.getMenu().getItem(1).getItemId());
                activityMainBinding.navView.setSelectedItemId(tabId);

            }
        }, 100);
    }

    /**
     *
     * @param id  tab ID
     * @param number 未读数
     */
    public void setTabUnread(int id, int number) {
        BadgeDrawable badgeDrawable = activityMainBinding.navView.getOrCreateBadge(id);
        if (number > 0) { // 设置则显示数字，不设置则显示点
            badgeDrawable.setNumber(number);
        }
        badgeDrawable.setBackgroundColor(getResources().getColor(R.color.color_dialog_button));
    }

    public void removeUnread(int id) {
        activityMainBinding.navView.removeBadge(id);
    }

    @Override
    public void onBackPressed() {
        if (activityMainBinding.navView.getSelectedItemId() == R.id.tab_mails) {
            Fragment fragment = getFragment(MailsBarFragment.class);
            if (fragment != null && (fragment instanceof MailsBarFragment)
                    && ((MailsBarFragment) fragment).onBackPressed()) {
                return;
            }
        }
        moveTaskToBack(true);
    }

    private void initFragAction() {
        getSupportFragmentManager().setFragmentResultListener("click_pab", this, this);
        getSupportFragmentManager().setFragmentResultListener("click_oab", this, this);
        getSupportFragmentManager().setFragmentResultListener(ScheduleFragment.INTO_CALENDAR_DETAIL, this, this);
    }

    @Override
    public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
        Intent mIntent;
        switch (requestKey) {
            case "click_oab":
                mIntent = new Intent(this, OabActivity.class);
                mIntent.putExtras(result);
                startActivity(mIntent);
                break;
            case "click_pab":
                mIntent = new Intent(this, PabActivity.class);
                startActivity(mIntent);
                break;
            case ScheduleFragment.INTO_CALENDAR_DETAIL:
                mIntent = new Intent(this, CalendarDetailActivity.class);
                mIntent.putExtras(result);
                startActivity(mIntent);
                break;
        }

    }

    public Fragment getFragment(Class<?> clazz) {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null && fragments.size() > 0) {
            NavHostFragment navHostFragment = (NavHostFragment) fragments.get(0);
            List<Fragment> childFragments = navHostFragment.getChildFragmentManager().getFragments();
            if (childFragments != null && childFragments.size() > 0) {
                for (int j = 0; j < childFragments.size(); j++) {
                    Fragment fragment = childFragments.get(j);
                    if (fragment.getClass().isAssignableFrom(clazz)) {
                        return fragment;
                    }
                }
            }
        }
        return null;
    }
//
//    @Override
//    public void onItemClick(int position, SimpleMail mail, Bundle extraData) {
//        MailViewModel model = new ViewModelProvider(this).get(MailViewModel.class);
//        model.select(mail);
//        LogUtil.d(TAG, mail.toString());
//        Intent intent = new Intent(this, ReadMailActivity.class);
//        intent.putExtra("position", position);
//        intent.putExtra("simpleMail", mail);
//        intent.putExtras(extraData);
//        Fragment fragment = getFragment();
//        if (fragment instanceof MailFragment) {
//            ((MailFragment) fragment).startNewPage(intent);
//        }
////        ReadMailActivity.start(this, position, mail);
//    }

    private Fragment getFragment() {
        NavHostFragment fragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        if (fragment == null) return null;
        return fragment.getChildFragmentManager().getPrimaryNavigationFragment();
    }

    // ===============  MailBarFragmentListener =================
    @Override
    public void onWriteClick() {
//        Bundle bundle = new Bundle();
//        bundle.putInt(MailComposeFragment.COMPOSE_MODE, MailComposeFragment.COMPOSE_MODE_WRITE);
//        MailComposeActivity.start(this, bundle);
    }

    @Override
    public boolean onMailSearchClick() {
        return false;
    }

    @Override
    public boolean onItemClick(int position, SimpleMail message, Bundle extraData) {
        return false;
    }

    @Override
    public void onEditPattern(boolean state) {
        if (state) {
            activityMainBinding.navView.setVisibility(View.GONE);
        } else {
            activityMainBinding.navView.setVisibility(View.VISIBLE);
        }
    }


    //=================== Contact1BarFragmentListener ==================
    @Override
    public boolean onContactsSearchClick(CustomPopWindow.PopItem popItem) {
        return false;
    }

    //================== ScheduleBarFragmentListener ==================
    @Override
    public void setCurrentSelectDate(Date date) {

    }

    @Override
    public void onItemClick(int index, CalListAccessedCalFolderResult.ListAccessedCalFolderModel model, MailCalendar mailCalendar2) {
        Intent mIntent = new Intent(this, CalendarDetailActivity.class);
        mIntent.putExtra("mail_calendar", mailCalendar2);
        mIntent.putExtra("index", index);
        if (model != null) {
            mIntent.putExtra("accessed_calfolder_model", model);
        }
        startActivity(mIntent);
    }


    private void startInitServie(int type) {
        final Context C = CApp.get();
        Intent intent = new Intent(C, InitService.class);
//        intent.setPackage(C.getPackageName());
//        intent.setAction(Actions.ACTION_INIT_SERVICE);
//        intent.putExtra("force_update", true);
        intent.putExtra("type", type);
        SystemUtil.compatStartService(C, intent);
    }
}